<!--
 * @Author: Mcc
 * @Date: 2024-07-11 10:21:23
 * @LastEditors: mcc 550539422@qq.com
 * @LastEditTime: 2024-08-22 18:58:28
 * @FilePath: \ft-apply\src\view\join\VolChoice.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by Mcc, All Rights Reserved. 
-->
<template>
  <div class="home">
    <div class="header" style="margin-top: -15vh; position: relative; height: 560px">
      <img src="../../assets/ui/img/index_top.png" alt="" />
    </div>
    <div class="content" style="margin-top: -20vh; position: relative">
      <commonLayout>
        <h3>志愿选择</h3>
        <van-form @submit="onSubmit" label-width="140px" rules="allRules" :validate-first="true">
          <van-cell-group inset>
            <van-field class="titles blues" readonly>
              <template #label>
                <div>第一意向城市<span>*</span></div>
              </template>
            </van-field>
            <van-field name="city1" v-model="formData.city1" is-link readonly label="" placeholder="选择"
              @click="clickShowPicker('city1')" :rules="allRules.city1"
              style='background: #f5f7fb;border-radius: 5px;color:#e3c0c8;' class="notLines" </van-field>

              <!-- <van-field class="titles" readonly>
              <template #label>
                <div>第1志愿<span>*</span></div>
              </template>
            </van-field> -->

              <van-field name="fieldValue1" v-model="formData.fieldValue1" is-link readonly label="第1志愿"
                placeholder="选择" @click="mulClickShowPicker('fieldValue1', '1')" :rules="allRules.fieldValue1">
              </van-field>

              <!-- <van-field class="titles" readonly>
              <template #label>
                <div>第2志愿<span>*</span></div>
              </template>
            </van-field> -->
              <van-field name="fieldValue2" v-model="formData.fieldValue2" is-link readonly label="第2志愿"
                placeholder="选择" @click="mulClickShowPicker('fieldValue2', '1')" :rules="allRules.fieldValue2">
              </van-field>
              <div style="height:20px;"></div>

              <van-field class="titles blues" readonly>
                <template #label>
                  <div>第二意向城市<span>*</span></div>
                </template>
              </van-field>
              <van-field name="city2" v-model="formData.city2" is-link readonly label="" placeholder="选择"
                @click="clickShowPicker('city2')" :rules="allRules.city2"
                style='background: #f5f7fb;border-radius: 5px;color:#e3c0c8;' class="notLines">
              </van-field>

              <!-- <van-field class="titles" readonly>
              <template #label>
                <div>第3志愿<span>*</span></div>
              </template>
            </van-field> -->

              <van-field name="fieldValue3" v-model="formData.fieldValue3" is-link readonly label="第3志愿"
                placeholder="选择" @click="mulClickShowPicker('fieldValue3', '2')" :rules="allRules.fieldValue3">
              </van-field>

              <!-- <van-field class="titles" readonly>
              <template #label>
                <div>第4志愿<span>*</span></div>
              </template>
            </van-field> -->
              <van-field name="fieldValue4" v-model="formData.fieldValue4" is-link readonly label="第4志愿"
                placeholder="选择" @click="mulClickShowPicker('fieldValue4', '2')" :rules="allRules.fieldValue4">
              </van-field>


              <div style="height: 15px;"></div>
              <van-field name="radio1" :rules="allRules.checked1">
                <template #label>
                  <div class="titles blues">地区是否接受调剂<span>*</span></div>
                </template>
                <template #input>
                  <van-radio-group v-model="formData.checked1" direction="horizontal">
                    <van-radio name="0">是</van-radio>
                    <van-radio name="1">否</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field name="radio2" :rules="allRules.checked2">
                <template #label>
                  <div class="titles blues">科目是否接受调剂<span>*</span></div>
                </template>
                <template #input>
                  <van-radio-group v-model="formData.checked2" direction="horizontal">
                    <van-radio name="0">是</van-radio>
                    <van-radio name="1">否</van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field name="radio3" :rules="allRules.checked3">
                <template #label>
                  <div class="titles blues">年级是否接受调剂<span>*</span></div>
                </template>
                <template #input>
                  <van-radio-group v-model="formData.checked3" direction="horizontal">
                    <van-radio name="0">是</van-radio>
                    <van-radio name="1">否</van-radio>
                  </van-radio-group>
                </template>
              </van-field>

              <!-- 单选城市 -->
              <van-popup v-model:show="showPicker" round position="bottom">
                <van-picker :columns="citys" @cancel="showPicker = false" @confirm="onConfirm" />
              </van-popup>
              <!-- 多选科目和年级 -->
              <van-popup v-model:show="mulShowPicker" round position="bottom">
                <van-picker :columns="subjectAges" @cancel="mulShowPicker = false" @confirm="mulConConfirm" />
              </van-popup>

              <!-- <van-field class="titles" readonly>
              <template #label>
                <div>第二意向城市<span>*</span></div>
              </template>
            </van-field>
            <van-field name="city2" v-model="formData.city2" is-link readonly label="" placeholder="选择"
              @click="clickShowPicker(1, 0)" :rules="allRules.fieldValue1">
            </van-field>

            <van-field class="titles" readonly>
              <template #label>
                <div>第3志愿<span>*</span></div>
              </template>
            </van-field>
            <van-field name="fieldValue2" v-model="formData.fieldValue3" is-link readonly label="" placeholder="选择"
              @click="clickShowPicker(2, 1)" :rules="allRules.fieldValue3">
            </van-field> -->

              <!-- <van-field class="titles" readonly>
              <template #label>
                <div>第三意向城市<span>*</span></div>
              </template>
            </van-field>
            <van-field name="city3" v-model="formData.city3" is-link readonly label="" placeholder="选择"
              @click="clickShowPicker(1, 0)" :rules="allRules.fieldValue1">
            </van-field> -->

              <!-- <van-field class="titles" readonly>
              <template #label>
                <div>第4志愿<span>*</span></div>
              </template>
            </van-field>
            <van-field name="fieldValue3" v-model="formData.fieldValue4" is-link readonly label="" placeholder="选择"
              @click="clickShowPicker(3, 1)" :rules="allRules.fieldValue4">
            </van-field> -->
              <!-- <van-popup v-model:show="showPicker" round position="bottom">
              <van-picker :columns="columns" @cancel="showPicker = false" @change="handleChange"
                @confirm="onConfirm2" />
            </van-popup> -->
          </van-cell-group>
          <div class="tips">
            每人仅允许填写一次志愿，请根据实际情况填写，提交成功后无法自助修改。如有特殊情况请及时与对应HR沟通。
          </div>
          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit" style="border: none;"> 确认 </van-button>
          </div>
        </van-form>
      </commonLayout>
    </div>
  </div>
</template>

  <script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import commonLayout from '../../components/CommonLayout.vue';
  import { data } from "./data"
  import { PickerOption, showDialog, showToast } from 'vant';
  import { useRouter } from 'vue-router';
  const router = useRouter();
  import apis from '../../api/index';
  const { saveUserVolunteer, userResumesList, selectCommonDictionary } = apis;
  import { localUserinfo } from '../../assets/js/common';
  const userInfo = localUserinfo();
  const showPicker = ref(false);
  const mulShowPicker = ref(false);
  const formData = ref({
    city1: '',
    city2: '',
    fieldValue1: '',
    fieldValue2: '',
    fieldValue3: '',
    fieldValue4: '',
    checked1: '',
    checked2: '',
    checked3: '',
  });
  // 用于标识是哪一个 field 被点击
  let pickerTarget = ref("");
  //管理城市的
  const citys = ref(
    []
  );
  //管理科目和学科的
  const subjectAges = ref([

  ])
  const clickShowPicker = async (target: string) => {
    //要在此记录点击的field，并且获取到对应的志愿
    pickerTarget.value = target;
    showPicker.value = true;
    const res = await selectCommonDictionary({
      "type": 0,
      "parentId": 0
    })

    const transformedArray = res.data.map((item: { label: any; }) => ({
      ...item, // 复制原始对象  
      text: item.label, // 添加新的属性 text，其值为原 label 的值  
    }));
    citys.value = transformedArray;
  }
  const selectcityId = ref("");
  const onConfirm = async ({ selectedOptions }) => {
    //确认提交的时候要提交
    formData.value[pickerTarget.value] = selectedOptions[0]?.text;
    selectcityId.value = selectedOptions[0]?.id;
    showPicker.value = false;
  };
  interface TreeNode {
    id: number;
    createTime?: Date | null;
    updateTime?: Date | null;
    isDeleted: number;
    parentId: number | string;
    children?: TreeNode[];
    label: string;
    value: string;
    level: number;
    type: number;
    text?: string; // 可选，因为可能已经在数据中存在或我们在转换过程中添加  
  }

  function transformLabelsToText(nodes: TreeNode[]): TreeNode[] {
    return nodes.map(node => {
      // 复制当前节点并添加/替换 text 属性  
      const transformedNode: TreeNode = {
        ...node,
        text: node.label, // 添加或替换 text 属性  
        // 注意：我们没有直接删除 label 属性，因为可能原始数据有其他用途  
        // 如果你确定不需要 label，可以添加 delete transformedNode.label;  

        // 递归处理子节点  
        children: node.children ? transformLabelsToText(node.children) : undefined,
      };

      // 如果确定不需要 label 属性，可以在这里删除它  
      // delete transformedNode.label;  

      return transformedNode;
    });
  }
  const mulClickShowPicker = async (target: string, citys: any) => {
    const names = "city" + citys;
    console.log(names)
    console.log(formData.value[names])
    if (formData.value[names] == '') {
      if (citys == "1") {
        showToast('请选择第一意向城市！');
        return false;
      } else {
        showToast('请选择第二意向城市！');
        return false;
      }
    }
    //要在此记录点击的field，并且获取到对应的志愿
    pickerTarget.value = target;
    mulShowPicker.value = true;
    const res = await selectCommonDictionary({
      "type": 0,
      "parentId": selectcityId.value//合肥id是1 芜湖是18
    })
    const getRes = res.data[0].children;
    const transformedArray = transformLabelsToText(getRes)
    console.log(transformedArray)
    subjectAges.value = transformedArray;
  }
  const mulConConfirm = async ({ selectedOptions }) => {
    console.log(selectedOptions)
    if (pickerTarget.value == "fieldValue1" || pickerTarget.value == "fieldValue2") {
      formData.value[pickerTarget.value] = formData.value.city1 + "-" + selectedOptions[0]?.text + "-" + selectedOptions[1]?.text;
    }
    if (pickerTarget.value == "fieldValue3" || pickerTarget.value == "fieldValue4") {
      formData.value[pickerTarget.value] = formData.value.city2 + "-" + selectedOptions[0]?.text + "-" + selectedOptions[1]?.text;
    }

    mulShowPicker.value = false;
  }

  // const getCitys = async (types, parentIds) => {
  //   const datas = await selectCommonDictionary({
  //     type: types,
  //     parentId: parentIds
  //   })
  //   citys.value = datas.data;
  //   console.log(datas)
  // }
  //getCitys();
  // const clickShowPicker = (types: any, parentIds: any) => {
  //   getCitys(types, parentIds)

  //   showPicker.value = true;
  //   //loopindexs.value = types;
  // };

  const getVitaId = async () => {
    console.log(userInfo.userId);
    const datas = await userResumesList({ userId: userInfo.userId })
    console.log(datas)
  }
  onMounted(() => {
    const clickStatus = JSON.parse(localStorage.getItem('clickStatus'));
    if (clickStatus.volunteerStatus == 2) {
      router.push("/");
    }
    getVitaId();
  })

  const loginValidator = (val: any, rule: any) => {
    return new Promise((resolve, reject) => {
      if (val === '') {
        showDialog({
          title: '温馨提示',
          message: rule.message,
        }).then(() => {
          return resolve(false);
        });
      } else {
        return resolve(true);
      }
    });
  };
  const allRules = reactive<any>({
    citys1: [{ validator: loginValidator, message: '请选择第一意向城市' }],
    citys2: [{ validator: loginValidator, message: '请选择第二意向城市' }],
    fieldValue1: [{ validator: loginValidator, message: '请选择第1志愿' }],
    fieldValue2: [{ validator: loginValidator, message: '请选择第2志愿' }],
    fieldValue3: [{ validator: loginValidator, message: '请选择第3志愿' }],
    fieldValue4: [{ validator: loginValidator, message: '请选择第4志愿' }],
    checked1: [{ validator: loginValidator, message: '请选择地区是否接收调剂' }],
    checked2: [{ validator: loginValidator, message: '请选择科目是否接收调剂' }],
    checked3: [{ validator: loginValidator, message: '请选择年级是否接收调剂' }],
  });


  // 定义一个接口来描述数组中的对象结构  
  interface Course {
    area: string;
    subject: string;
    grade: string;
  }

  // 将字符串分割并转换为对象
  const parseCourse = (value: string): Course => {
    const [area, subject, grade] = value.split('-');
    return { area, subject, grade };
  };
  const onSubmit = async (values: any) => {
    const clickStatus = JSON.parse(localStorage.getItem('clickStatus'));
    const arr1 = parseCourse(values.fieldValue1);
    const arr2 = parseCourse(values.fieldValue2);
    const arr3 = parseCourse(values.fieldValue3);
    const arr4 = parseCourse(values.fieldValue4);

    // 使用parseFieldValue函数来创建CourseInfo对象数组  
    // const courseInfos: CourseInfo[] = [
    //   parseFieldValue(values.fieldValue1),
    //   parseFieldValue(values.fieldValue2),
    //   parseFieldValue(values.fieldValue3),
    //   parseFieldValue(values.fieldValue4)
    // ];
    // console.log(courseInfos);
    const upData = {
      "resumesId": clickStatus.resumesId,
      "volunteerList": [arr1, arr2, arr3, arr4],
      "areaIsAdjust": values.radio1,
      "subjectIsAdjust": values.radio2,
      "gradeIsAdjust": values.radio3,
    }
    console.log(upData)
    console.log('submit', values);
    const res = await saveUserVolunteer(upData);
    showToast("提交成功！ ")
    router.push({
      path: '/delivered',
      query: {
        identifier: 'contract',
      },
    });
  };
</script>

  <style lang="less" scoped>
  :root {
    --van-button-primary-background: #79c5ef;
  }

  .notLines {
    &::after {
      border: none;
    }
  }

  #app {
    background: #ffffff !important;
  }

  img {
    width: 100%;
  }

  :deep(.van-swipe__indicator) {
    background: rgba(32, 158, 228, 0.8);
    width: 10px;
    height: 10px;
  }

  :deep(#layout) {
    background: #fff;
    padding: 0;
    box-shadow: 0px 0 0 rgba(255, 255, 255, 1);
  }

  h3,
  .tips {
    margin: 28px 20px 10px 0px;
    padding-left: 20px;
  }

  .tips {
    font-weight: 400;
    font-size: 14px;
    color: #b3c0c8;
    margin: 20px 20px 10px 0px;
  }

  .blues {
    :deep(.van-field__label) {
      color: #209ee4 !important;
      font-size: 17px;
      font-weight: 600;
      letter-spacing: 0px;
      margin-bottom: 10px;
    }
  }

  .content {
    height: 63vh;

    :deep(.van-cell-group) {
      margin: 0 10px;
    }

    .titles {
      margin: 0px;
      padding-bottom: 0px;
      padding-top: 0px;


      span {
        color: #ff4242;
      }
    }

    :deep(.titles:after) {
      border: none;
    }

    :deep(.van-button) {
      border-radius: 8px;
      background: #209ee4;
      border-radius: 10px 10px 10px 10px;
    }
  }
</style>
